<?php


namespace app\admin\controller;


use think\Controller;
use app\common\model\Options as OptionsModel;


class OptionsController extends Controller
{
    public function index($type=1)
    {
        $params = $this->request->get();
        // $options = OptionsModel::all();
        $optionsModel = new OptionsModel();
        $options = OptionsModel::where(['type'=>$type])->select();
        $this->assign('options', $options);
        return $this->fetch();
    }

    public function create()
    {
        if ($this->request->isGet()){
            return $this->fetch();
        }

        $postData = $this->request->post();


        $options = OptionsModel::get(['name' => $postData['name']]);
        if (!is_null($options)) {
            return json(['code' => 4000, 'message' => '该选项已存在']);
        }

        $options = new OptionsModel();
        if ($options->allowField(true)->validate(true)->save($postData)) {
            return json(['code' => 0, 'message' => '添加成功']);
        }
        return json(['code' => 4000, 'message' => '添加失败']);
    }

    public function update($type, $id)
    {
        echo $type, $id;
        return $this->fetch();
    }

    public function delete()
    {
        $options_id = $this->request->get('id');
        $auth = OptionsModel::get($options_id);
        if ($auth->delete()) {
            return json(['code' => 0, 'message' => '删除成功']);
        }

        return json(['code' => 4000, 'message' => '删除失败' . $auth->getError()]);
    }
}